﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace CSharpPaint.DrawComponents
{
    class Line : DrawableComponent
    {
        public Line(int x1, int y1, Color color)
            : base(x1, y1, color)
        {
            this.Dots = new Dot[2];
            this.Dots[0] = new Dot(x1, y1);
        }

        public Line(int x1, int y1)
            : this(x1, y1,Color.Black)
        {
        }

        public override void DrawLastDot(int x2, int y2)
        {
            this.Dots[1] = new Dot(x2, y2);
            Bresenham(Dots[0].X, Dots[0].Y, Dots[1].X, Dots[1].Y);
        }

        public void Bresenham(int x1, int y1, int x2, int y2)
        {
            Pixels.Clear();
            int slope;
            int dx, dy;
            int incE, incNE;
            int d, x, y;
            
            if (x1 > x2)
            {
                Bresenham(x2, y2, x1, y1);
                return;
            }
            dx = x2 - x1;
            dy = y2 - y1;

            if (dy < 0)
            {
                slope = -1;
                dy = -dy;
            }
            else            
                slope = 1;            
            

            incE = 2 * dy;
            incNE = incE - 2 * dx;
            d = incE - dx;
            y = y1;

            for (x = x1; x <= x2; x++)
            {
                Pixels.Add(new Dot(x, y));

                if (d <= 0)
                    d += incE;
                
                else
                {
                    d += incNE;
                    y += slope;
                }
            }
        }

        public override int Length()
        {
            throw new NotImplementedException();
        }

        

        public override int Height()
        {
            if (Y2 > Y1)
                return Y2 - Y1;

            else if (Y2 < Y1)
                return Y1 - Y2;

            else return 0;
        }

        public override int Width()
        {
            if (X2 > X1)
                return X2 - X1;

            else if (X2 < X1)
                return X1 - X2;

            else return 0;
        }
    }
}
